<template>
  <div class="wrapper">
    <!-- 三级分类切换 -->
    <div class="switch-tab" ref="topSwitch">
      <ul ref="topSwitchUl">
        <li v-for="(item, index) in mainCateGory"
          :key="index"
          :class="{'active': currentCateGory === item.idx}"
          ref="topSwitchItem"
          @click="changeCategory(item.idx, index)">{{item.name}}</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
export default {
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.currentCateGory = to.params.id
      vm.getMainCateGory(to.params.id)
    })
  },
  mounted () {
  },
  data () {
    return {
      currentCateGory: null,
      mainCateGory: [],
      cateGoryList: []
    }
  },
  methods: {
    getMainCateGory (id) {
      this.$reqPost('Category/categoryList', {
        parentId: id
      }).then(json => {
        if (json.error === '00') {
          let categoryFirst = json.data
          for (let i = 0; i < categoryFirst.length; i++) {
            this.mainCateGory = this.mainCateGory.concat(categoryFirst[i].thirdCategory)
          }
          this.currentCateGory = this.mainCateGory[0].idx
          this.initTabScroll()
        }
      })
    },
    initTabScroll () {
      this.$nextTick(() => {
        let width = 0
        for (let i = 0; i < this.mainCateGory.length; i++) {
          width += this.$refs.topSwitchItem[i].getBoundingClientRect().width
        }
        this.$refs.topSwitchUl.style.width = width + 'px'
        this.topScroll = new BScroll(this.$refs.topSwitch, {
          startX: 0,
          click: true,
          scrollX: true,
          scrollY: false
        })
        console.log(this.topScroll)
      })
    },
    changeCategory (id, index) {
      this.currentCateGory = id
      this.topScroll.scrollToElement(this.$refs.topSwitchItem[index], 1000)
    }
  }
}
</script>
<style lang="less" scoped>
.switch-tab{
  height: 80*@rex;
  overflow-x: auto;
  overflow-y: hidden;
  background: @white;
  ul{
    overflow: hidden;
    li{
      float: left;
      line-height: 80*@rex;
      font-size: 28*@rex;
      padding: 0 20*@rex;
      color: @text-black;
      position: relative;
      &.active{
        color: @text-red;
      }
      &.active:after{
        content: '';
        width: 100%;
        height: 6*@rex;
        background: @text-red;
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }
  }
}
</style>
